var isPostBack=true;
//初始化告警类型和告警管理列表
// $(function() {
//故障告警列表
// faultAlarmList(1);
//加载告警类别下拉框
// warningDictionaryType();
// });

//故障告警查询点击事件
$("#btnSearchFaultAlarm").on("click",function(){
    isPostBack=true;
    faultAlarmList(1);
});

var eventProcessStatus=1;
$("#myTabs li").on("click", function () {
    isPostBack=true;
    eventProcessStatus=$(this).index()+1;
    $(".bg-date").val("");
    // $("#diName").val("");
    faultAlarmList(1);
});

//故障告警
function faultAlarmList(pageIndex){
    // var diName=$("#diName").val();
    var startApplyTime=$("#startApplyTime").val();
    var endApplyTime=$("#endApplyTime").val();
    var eventDescribe=$("#eventDescribeFault").val();
    if("undefined" == typeof startApplyTime){
        startApplyTime="";
    }
    if("undefined" == typeof endApplyTime){
        endApplyTime="";
    }
    if("undefined" == typeof eventDescribe){
        eventDescribe="";
    }
    // if(diName==null){
    //     var diName="";
    // }
    $.getJSON('/cwp/src/json/warning/warningEvent_c001_2.json',function(data){
        var loaderFaultAlarmTab = new LoaderTable("faultAlarmLoader","faultAlarmTab","/cwp/front/sh/warningEvent!execute","uid=c001_2&startApplyTime="+startApplyTime+"&endApplyTime="+endApplyTime+"&dictValue="+dictValue+"&eventProcessStatus="+eventProcessStatus+"&eventType=1&eventDescribeFault="+eventDescribe,pageIndex,10,faultAlarmResultArrived,"","frmSearch");
        loaderFaultAlarmTab.loadSuccessed(data);
    });
    // loaderFaultAlarmTab.Display();
}

//发送告警信息回调函数
function faultAlarmResultArrived(result)
{
    var thead_tr="";
    if(result.beans[0].eventProcessStatus!="3"){
        thead_tr="<th>时间差</th>";
    }else{
        thead_tr="";
    }
    var thead="<thead>"+
        "<tr>"+
        "<th width='14%'>告警编号</th>"+
        "<th>类别</th>"+
        "<th width='10%'>位置</th>"+
        "<th>来源</th>"+
        "<th>告警级别</th>"+
        "<th width='28%'>故障描述</th>"+
        "<th>时间</th>"+
        //result.beans[0].eventProcessStatus!="3"?"<th>时间差</th>":""
        thead_tr+
        "<th>状态</th>"+
        "<th>操作</th>"+
        "</tr>"+
        "</thead>";
    //拼接表格列表html
    var tbodys = "<tbody>";
    for(var i=0;i<result.beans.length;i++){
        var orsystem="";
        var state="";
        var level="";
        if(result.beans[i].eventFromSystem=="1"){
            orsystem="系统";
        }else{
            orsystem="手动";
        }
        if(result.beans[i].warningLevel=="3"){
            level="紧急"
        }else if(result.beans[i].warningLevel=="2"){
            level="高"
        }else if(result.beans[i].warningLevel=="1"){
            level="中"
        }else if(result.beans[i].warningLevel=="0"){
            level="低"
        }

        var state_td="";
        if(result.beans[i].eventProcessStatus=="1"){
            state="未处理";
            state_td="<td>"+result.beans[i].datedifferent+"</td>";
        }else if(result.beans[i].eventProcessStatus=="2"){
            state="处理中";
            state_td="<td>"+result.beans[i].datedifferent+"</td>";
        }else if(result.beans[i].eventProcessStatus=="3"){
            state="已处理";
            state_td="";
        }

        tbodys+="<tr>" +
            "<td>"+result.beans[i].alarmNumber+"</td>"+
            "<td>"+result.beans[i].deviceName+"</td>"+
            "<td>"+result.beans[i].buildingName+"</td>"+
            "<td>"+orsystem+"</td>"+
            "<td>"+level+"</td>"+
            "<td>"+result.beans[i].eventDescribe+"</td>"+
            "<td>"+result.beans[i].applyTime+"</td>"+
            state_td+
            "<td>"+state+"</td>"+
            "<td><a class='t-btn t-btn-sm t-btn-blue t-btn-deal' onclick=detailSelect('"+result.beans[i].warningEventId+"')>详情</a></td></tr>";
    }
    tbodys += "</tbody>";
    //显示表格html
    $("#faultAlarmTab").html(thead+tbodys);
}



/**
 * post提交数据
 * 发送地址，uid，action行为，成功回调函数，失败回调函数
 *@author cheqniuxu
 *@created 2016/05/31
 *通过字典表查询字典数据表告警类别
 */
// function warningDictionaryType(){
//     PostForm("/cwp/front/sh/warningEvent!execute", "uid=c002_5&dictKey=intelligentType&dictdataKey='security','building_services'", "", WarningDictionarytResultArrived, '',"frmMain");
// }

// function WarningDictionarytResultArrived(result) {
// console.log(result);
// // var sel = $("#diName");
// var option = ""
// sel.empty();
// option = $("<option>").text("请选择").val("");
// sel.append(option);
// for (var i = 0; i < result.beans.length; i++) {
//     if (result.beans[i].dictdataValue != "1004001") {
//         option = $("<option>").text(result.beans[i].dictName).val(result.beans[i].dictValue);
//         sel.append(option);
//     }
// }
// }



//当前页，加载容器
function paginationCallback(page_index){
    if(!isPostBack) {
        faultAlarmList(page_index+1);
    }
}

/**
 * 点击详情
 * @param warningEventId   告警事件id
 */

var modalHtml="";
$(function(){
    modalHtml=$("#modalDetailsAlarm").html();
});

function detailSelect(warningEventId){
    $("#modalDetailsAlarm").html(modalHtml);
    // PostForm("/cwp/front/sh/warningEvent!execute", "uid=c003_3&warningEventId="+warningEventId, "", detailWarningById, '');
    $.getJSON('/cwp/src/json/warning/warningEvent_c003_3.json',function(data){
        detailWarningById(data);
    })
}

function detailWarningById(result){
    if(result.returnCode == 0){

        var state="";
        var warningLevelHtml="";
        //当前事件状态
        if(result.bean.eventProcessStatus=="1"){
            state="未处理"
        }else if(result.bean.eventProcessStatus=="2"){
            state="处理中"
        }else if(result.bean.eventProcessStatus=="3"){
            state="已处理"
        }
        //设备类型
        var deviceName="";
        switch (result.bean.warningType){
            case "1003185":
                deviceName="空调机组";
                break;
            case "1003186":
                deviceName="送排风机";
                break;
            case "1003187":
                deviceName="集水坑";
                break;
            case "1003189":
                deviceName="生活给水";
                break;
            case "1003190":
                deviceName="智能门禁";
                break;
            case "1004":
                deviceName="门禁";
                break;
            case "1005":
                deviceName="照明设备";
                break;
            case "1006":
                deviceName="能耗";
                break;
            case "1010":
                deviceName="视频监控";
                break;
            case "1003191":
                deviceName="动环设备";
                break;
            default:
                break;
        }


        //$('#deviceType').html(result.bean.deviceName==""?"无":result.bean.deviceName);
        $('#deviceType').html(deviceName);

        //设备状态
        $('#deviceState').html(state);
        //告警级别warningLevel

        //当前责任人及角色
        var noticeNameArray=result.bean.appPush.split(',');
        if(result.bean.responseName!=""){
            $(".responsibe-name").html(result.bean.responseName);
            $(".responsibe-role").html(result.bean.response.split(',')[0]);
            $(".responsibe-phone span").html(result.bean.responsePhone);
        }
        else{
            $(".responsibe-name").html("暂无人接单");
            //$(".responsibe-name").html(noticeNameArray[1].split(':')[1]);
            //$(".responsibe-role").html(noticeNameArray[1].split(':')[0]);
        }

        //人员详情ID
        //$(".btn-user-info").attr("id",result.bean.responseOfficerId);

        //告警编号
        $("#alarmNumber").html(!result.bean.alarmNumber ?"无":result.bean.alarmNumber);
        //告警级别
        if(result.bean.warningLevel==0){
            warningLevelHtml="<i class='t-tag-del'>低</i>"
        }

        switch (result.bean.warningLevel){
            case "0":
                warningLevelHtml="<i class='t-tag-del'>低</i>";
                break;
            case "1":
                warningLevelHtml="<i class='t-tag-yellowColor'>中</i>";
                break;
            case "2":
                warningLevelHtml="<i class='t-tag-ing'>高</i>";
                break;
            case "3":
                warningLevelHtml="<i class='t-tag-red'>紧急</i>";
                break;
            default:
                break;
        }

        $("#messageLevel").html(warningLevelHtml);

        $('#devicePostion').html(result.bean.buildingName==""?"无":result.bean.buildingName);

        $('#warningDescribe').html(result.bean.eventDescribe==""?"无":result.bean.eventDescribe);

        $('#handleOpinion').html(result.bean.handleOpinion==""?"未完成":result.bean.handleOpinion);

        if(result.bean.applyTime!=""){
            $('#noticeTime').html(result.bean.applyTime);
            $('#noticeName').html(noticeNameArray[1]+"<br/>"+noticeNameArray[0]);
        }

        if(result.bean.responseTime!=""&&result.bean.responseName!=""){
            $('#responseTime').html(result.bean.responseTime);
            $('#responseName').html(result.bean.response.split(',')[0]+"："+result.bean.responseName);
        }

        if(result.bean.handleTime!=""){
            $('#handlerTime').html(result.bean.responseTime);
            $('#handlerName').html(result.bean.response.split(',')[0]+"："+result.bean.responseName);
        }

        if(result.bean.eventProgress=="2"){
            $('.bubble').eq(1).removeClass("comp");
            $('.com_squ').eq(1).removeClass("conp");
        } else if(result.bean.eventProgress == "3"){

            $('.bubble').eq(1).removeClass("comp");
            $('.bubble').eq(2).removeClass("comp");
            $('.bubble').eq(3).removeClass("comp");
            $('.com_squ').eq(1).removeClass("conp");
            $('.com_squ').eq(2).removeClass("conp");
            $('.com_squ').eq(3).removeClass("conp");
            $('.line .end').removeClass("conp");
            $('#completeTime').html(result.bean.handleTime);
            $('#completeResultStaus').html("已完成");
            $('#completeResult').html("")

        } else if(result.bean.eventProgress == "4"){
            $('.bubble').eq(1).removeClass("comp");
            $('.bubble').eq(2).removeClass("comp");
            $('.bubble').eq(3).removeClass("comp");
            $('.com_squ').eq(1).removeClass("conp");
            $('.com_squ').eq(2).removeClass("conp");
            $('.com_squ').eq(3).removeClass("conp");
            $('.line .end').removeClass("conp");
            $('#completeTime').html(result.bean.handleTime);
            $('#completeResultStaus').html("已完成");
            $('#completeResult').html("转工单")

        }

        // 动环详情
        if (result.bean.warningType == '1003191') {
            $('#modalDetailsAlarm .t-columns-group').append('<li> <label>操作: </label> <span class="t-btn t-btn-deal" style="margin-left: 10px;" onClick="showDetail(\'' + result.bean.eventDeviceId + '\')">查看详情</span> </li>')
        }

        //getStaffRole(result.bean.warningCategoryId);
        $("#modalDetailsAlarm").modal({
            keyboard: true,
            backdrop: 'static'
        }).on('show.bs.modal', centerModal());
        $(window).on('resize', centerModal());
    }
}

// function getStaffRole(warningCategoryId){
//     PostForm("/cwp/front/sh/warningEvent!execute", "uid=c008&warningCategoryId="+warningCategoryId,"", StaffRoleResultArrived, '');
// }
//
//
// function StaffRoleResultArrived(result){
//     var appInfo="";
//     for(var i=0;i<result.beans.length;i++){
//         appInfo+=result.beans[i].roleName+":"+result.beans[i].appPush+"</br>"
//     }
//     $('#noticeName').html(appInfo);
// }


/*
 * post提交数据
 * 发送地址，uid，action行为，成功回调函数，失败回调函数
 *@author cheqniuxu
 *@created 2016/05/31
 *通过字典表查询字典数据表告警类别
 * */

$(function() {
    //warningDictionaryType();
    //验证
    eventValidtor();
});

//function warningDictionaryType(){
//    PostForm("/cwp/front/sh/warningEvent!execute", "uid=c002_5&dictKey=intelligentType&dictdataKey='security','building_services'", "", WarningDictionarytResultArrived, '');
//}
//
//function WarningDictionarytResultArrived(result){
//    var sel = $("#diName");
//    var option = ""
//    sel.empty();
//    option = $("<option>").text("请选择").val("");
//    sel.append(option);
//    for ( var i = 0; i <   result.beans.length; i++) {
//        option = $("<option>").text(result.beans[i].dictName).val(result.beans[i].dictValue);
//        sel.append(option);
//    }
//}

//-----------------新增开始--------------------------//
//获取设备类别
// function addWarningDictionaryType(){
//     PostForm("/cwp/front/sh/warningEvent!execute", "uid=c002_5&dictKey=intelligentType&dictdataKey='security','building_services'", "", AddWarningDictionarytResultArrived, '');
// }
// //获取设备类别回调函数
// function AddWarningDictionarytResultArrived(result){
//     var sel = $("#addWaringType");
//     var option = "";
//     sel.empty();
//     option = $("<option>").text("请选择").val("");
//     sel.append(option);
//     for ( var i = 0; i <   result.beans.length; i++) {
//         if (result.beans[i].dictValue != "1004"){
//             option = $("<option>").text(result.beans[i].dictName).val(result.beans[i].dictValue);
//             sel.append(option);
//         }
//     }
// }

//选择设备显示楼栋
$("#addWaringType").on("change",function(){
    $("#buildingNo").val("");
    $(".buildingChildLi").addClass("hide");
    $("#buildingChild").html("<option>请选择</option>");
    $(".buildingRoomLi").addClass("hide");
    $("#buildingRoom").html("<option>请选择</option>");
    $(".devicesLi").addClass("hide");
    $("#device").html("<option>请选择</option>");
    $(".buildingNoLi").removeClass("hide");
    // var result=$(this).val();
    // if(result!=""){
    // }
});

//物业管理-新增
////查找所有楼栋 chenqiuxu
function buildingQuary(){
    // PostForm("/cwp/front/sh/warningEvent!execute", "uid=c004_3", "", buildingResultArrived, '');
    $.getJSON('/cwp/src/json/warning/warningEvent_c004_3.json',function(data){
        buildingResultArrived(data);
    });
}
//获取所有楼栋并拼接html
function buildingResultArrived(result){
    var sel = $("#buildingNo");
    var option = "";
    sel.empty();
    option = $("<option>").text("请选择").val("");
    sel.append(option);
    for ( var i = 0; i <   result.beans.length; i++) {
        option = $("<option>").text(result.beans[i].buildingDesc).val(result.beans[i].buildingId);
        sel.append(option);
    }
}

//根据楼，显示层，显示房间，三级联动
$("#buildingNo").on("change",function(){
    var parentId=$(this).val();
    if(parentId!=""){
        // PostForm("/cwp/front/sh/warningEvent!execute", "uid=c005_2&parentId="+parentId, "", bParentResultArrived, '');
        $.getJSON('/cwp/src/json/warning/warningEvent_c005_2.json',function(data){
            bParentResultArrived(data);
        })
    }else{
        $(".buildingChildLi").addClass("hide");
    }
});

//显示层
function bParentResultArrived(result){
    $(".buildingChildLi").addClass("hide");
    $("#buildingChild").html("<option>请选择</option>");
    $(".buildingRoomLi").addClass("hide");
    $("#buildingRoom").html("<option>请选择</option>");
    $(".devicesLi").addClass("hide");
    $("#device").html("<option>请选择</option>");
    if(result.returnCode=="0" && result.beans.length>0){

        var sel = $("#buildingChild");
        var option = "";
        sel.empty();
        option = $("<option>").text("请选择").val("");
        sel.append(option);
        for ( var i = 0; i <   result.beans.length; i++) {
            option = $("<option>").text(result.beans[i].buildingDesc).val(result.beans[i].buildingId);
            sel.append(option);
        }
        $(".buildingChildLi").removeClass("hide");
    }
    else{
        tipModal("icon-cross", "查询失败，该建筑无相应设备");
    }

}
//显示房间
$("#buildingChild").on("change",function(){
    var count = $(this).val();
    $(".buildingRoomLi").addClass("hide");
    $("#buildingRoom").html("<option>请选择</option>");
    $(".devicesLi").addClass("hide");
    $("#devices").html("<option>请选择</option>");
    var deviceType=dictValue;
    // var deviceType=$("#addWaringType").val();
    if(count!=""){
        var parentId = $(this).children('option:selected').val();
        //获取楼层
        // PostForm("/cwp/front/sh/warningEvent!execute", "uid=c005_2&parentId="+parentId, "", bRoomResultArrived, '');
        $.getJSON('/cwp/src/json/warning/warningEvent_c005_2.json',function(data){
            bRoomResultArrived(data);
        })
        // PostForm("/cwp/front/sh/device!execute", "uid=d014_2&buildingId="+parentId+"&deviceType="+deviceType, "", deviceBuildingResultArrived, '');
    }else{
        $(".buildingRoomLi").addClass("hide");
        $("#buildingRoom").html("<option>请选择</option>");
    }
});
//选择层后，加载楼层，加载设备

//显示房间
function bRoomResultArrived(result){
    if(result.beans.length>0 && result.returnCode=="0"){
        var sel = $("#buildingRoom");
        var option = "";
        sel.empty();
        option = $("<option>").text("请选择").val("");
        sel.append(option);
        for ( var i = 0; i <   result.beans.length; i++) {
            option = $("<option>").text(result.beans[i].buildingDesc).val(result.beans[i].buildingId);
            sel.append(option);
        }
        $(".buildingRoomLi").removeClass("hide");
    }
    else{
        var buildingId=$("#buildingChild").val();
        var deviceType=dictValue;
        // var deviceType=$("#addWaringType").val();
        if(buildingId!="" && deviceType!="" && $.formValidator.IsOneValid('addWaringType')){
            // PostForm("/cwp/front/sh/device!execute", "uid=d001&buildingId="+buildingId+"&deviceType="+deviceType, "", deviceResultArrived, '');
            $.getJSON('/cwp/src/json/warning/device_d001.json',function(data){
                deviceResultArrived(data);
            })
        }
    }

}

/**
 *读取设备
 * 1、判断房间是否有值
 * 如果房间被选择，开始进行请求数据
 */

$(function () {
    $("#buildingRoom").change(function(){
        var buildingId = $(this).val();
        var deviceType = dictValue;
        // var deviceType = $("#addWaringType").val();
        if(buildingId != "" && deviceType != null){
            // PostForm("/cwp/front/sh/device!execute", "uid=d001&buildingId="+buildingId+"&deviceTypeId="+deviceType + "&currentPage=1&pageSize=1000&deviceName=&devicePositionCode=&isDeviceControl=", "", deviceResultArrived, '');
            $.getJSON('/cwp/src/json/warning/device_d001.json',function(data){
                deviceResultArrived(data);
            })
        }else{
            $(".devicesLi").addClass("hide");
            $("#device").html("<option>请选择</option>");
        }
    })
});

//根据楼层显示所有设备
function deviceBuildingResultArrived(result){
    if(result.beans.length>0 && result.returnCode == 0){
        var sel = $("#devices");
        var option = "";
        sel.empty();
        option = $("<option>").text("请选择").val("");
        sel.append(option);
        for ( var i = 0; i <   result.beans.length; i++) {
            option = $("<option>").text(result.beans[i].devicePositionCode).val(result.beans[i].deviceId);
            sel.append(option);
        }
        $(".devicesLi").removeClass("hide");
    } else {
        tipModal('icon-cross', result.returnMessage)
    }
}

//显示所有设备
function deviceResultArrived(result){
    if(result.beans.length>0 && result.returnCode == 0){
        var sel = $("#devices");
        var option = "";
        sel.empty();
        option = $("<option>").text("请选择").val("");
        sel.append(option);
        for ( var i = 0; i <   result.beans.length; i++) {
            option = $("<option>").text(result.beans[i].devicePositionCode).val(result.beans[i].deviceId);
            sel.append(option);
        }
        $(".devicesLi").removeClass("hide");
    }else{
        tipModal("icon-cross", '当前楼层无设备！');
        $("#devices").html("<option>请选择</option>");
        $(".devicesLi").addClass("hide");
    }

}

//验证
function eventValidtor()
{
    $.formValidator.initConfig({
        formid: "frmMain", onerror: function (msg) {
            return false;
        }, onsuccess: function () {
            return true;
        }
    });

    $("#addDetailDesc").formValidator({
        onfocus: "请输入故障描述",
        oncorrect: " "
    }).InputValidator({
        min:4,
        max: 100,
        onempty: "请输入故障描述",
        onerror: "描述长度为4-100个字符"
    });

    // $("#addWaringType").formValidator({
    //     onfocus:"请选择设备类别",
    //     oncorrect:"&nbsp;"
    // }).InputValidator({
    //     min:1,
    //     onempty:"请选择设备类别",
    //     onerror: "请选择设备类别"
    // });

    $("#addLevel").formValidator({
        onfocus:"请选择告警级别",
        oncorrect:"&nbsp;"
    }).InputValidator({
        min:1,
        onempty:"请选择告警级别",
        onerror: "请选择告警级别"
    });

    $("#buildingNo").formValidator({
        onfocus:"请选择楼栋",
        oncorrect:"&nbsp;"
    }).InputValidator({
        min:1,
        onempty:"请选择楼栋",
        onerror: "请选择楼栋"
    });

    $("#buildingChild").formValidator({
        onfocus:"请选择楼层",
        oncorrect:"&nbsp;"
    }).InputValidator({
        min:1,
        onempty:"请选择楼层",
        onerror: "请选择楼层"
    });

    $("#devices").formValidator({
        onfocus:"请选择设备",
        oncorrect:"&nbsp;"
    }).InputValidator({
        min:1,
        onempty:"请选择设备",
        onerror: "请选择设备"
    });
}

//添加告警事件
function saveWarningEvent() {
    //判断表单验证是否通过
    if ($.formValidator.PageIsValid()) {
        var applierId = localStorage.getItem("parkId");
        // PostForm("/cwp/front/sh/warningEvent!execute", "uid=c006_2&applierId="+applierId+"&eventProgress=1&eventType=1&warningType=" + dictValue, "", saveWarningEventResultArrived, '',"frmMain");
        $.getJSON('/cwp/src/json/warning/warningEvent_c006_2.json',function(data){
            saveWarningEventResultArrived(data);
        })
        //关闭模态框
        $("#modalMaintenanceNew").modal("hide");
    }
}
//saveWarningEventResultArrived
function saveWarningEventResultArrived(result){
    switch (result.returnCode) {
        case "0":
            tipModal("icon-checkmark", "添加成功");
            isPostBack=true;
            faultAlarmList(1);
            break;
        case "2":
            tipModal("icon-cross", "添加失败");
            break;
        case "-9999":
            tipModal("icon-cross", "添加失败");
            break;
        default:
            break;
    }
}
////绑定点击事件
//新建
$("#btnMaintenanceNew").on("click", function () {
    //告警类型
    // addWarningDictionaryType();
    buildingQuary();
    $(".tipArea div").html("").attr("class","");
    $("#modalMaintenanceNew select").val("");
    $("#addDetailDesc").val("");
    $("#buildingNo").val("");
    // $(".buildingNoLi").addClass("hide");
    // $(".buildingChildLi").addClass("hide");
    $("#buildingChild").html("<option>请选择</option>");
    // $(".buildingRoomLi").addClass("hide");
    $("#buildingRoom").html("<option>请选择</option>");
    // $(".devicesLi").addClass("hide");
    $("#device").html("<option>请选择</option>");
    $("#modalMaintenanceNew").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal');
    //}).on('show.bs.modal', centerModal());
    //$(window).on('resize', centerModal());
});
//-------------新增结束---------------------//